package com.dataStore.config.dataSources;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

@Configuration
@MapperScan(basePackages = "com.dataStore.business.dao", sqlSessionTemplateRef = "devSqlSessionTemplate")
public class DevConfig {

	@Bean(name = "devDataSource")
	@ConfigurationProperties(prefix = "spring.datasource.dev")
	@Primary
	public DataSource devDataSource() {
		return DataSourceBuilder.create().build();
	}

	@Bean(name = "devSqlSessionFactory")
	@Primary
	public SqlSessionFactory devSqlSessionFactory(@Qualifier("devDataSource") DataSource dataSource)
			throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:com/dataStore/business/dao/*.xml"));
		bean.setTypeAliasesPackage("com.dataStore.domain");
		return bean.getObject();
	}

	@Bean(name = "devTransactionManager")
	@Primary
	public DataSourceTransactionManager devTransactionManager(@Qualifier("devDataSource") DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}

	@Bean(name = "devSqlSessionTemplate")
	@Primary
	public SqlSessionTemplate devSqlSessionTemplate(
			@Qualifier("devSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
		return new SqlSessionTemplate(sqlSessionFactory);
	}
}
